/**
 * Created by mj on 2017/3/30.
 */
$(function () {
    $('#dglist').datagrid({
        url: "processFlowQueryWithPaging",
        method: "post",
        title: "工艺流程卡列表",
        striped: true,
        singleSelect: true,
        rownumbers: true,
        loadMsg: "努力加载中...",
        fit: true,
        fitColumns: true,//是否自动填充适合屏幕
        pagination: true,//是否显示底部分页工具栏
        pageSize: 15,
        pageList: [15, 20, 25],
        showFooter: true,
        autoRowHeight: false,
        columns: [[
            {field: 'id', hidden: 'true'},
            {field: 'serialNumber', title: '序号', sortable: true, width: 100, align: "center"},
            {field: 'materialNumber', title: '物料编号', sortable: true, width: 100, align: "center"},
            {field: 'partName', title: '零件名称', sortable: true, width: 100, align: "center"},
            {field: 'material', title: '材质', sortable: true, width: 100, align: "center"},
            {field: 'materialSpec', title: '原材料规格', sortable: true, width: 100, align: "center"},
            {field: 'chartNumber', title: '图纸编号', sortable: true, width: 100, align: "center"},
            {field: 'oderNumber', title: '数量', sortable: true, width: 50, align: "center"},
            {field: 'unit', title: '单位', sortable: true, width: 50, align: "center"},
            {field:'arrivalDate',title:'到货日期',
                formatter:function(value,row,index){
                    var unixTimestamp = new Date(value);
                    return unixTimestamp.toLocaleString();
                }
            },
            {field: 'remarksFig', title: '备注/附图', sortable: true, width: 100, align: "center"}
        ]],
        toolbar: [
            {
                text: '增加', iconCls: 'icon-add', handler: function () {
                openAddTechnologyWin();
            }
            }, '-',
            {
                text: '修改基本信息', iconCls: 'icon-edit', handler: function () {
                editProject();
            }
            }, '-',
            {
                text: '修改项目工艺', iconCls: 'icon-edit', handler: function () {
                openEditTechnologyListWin();
            }
            }, '-',
            {
                text: '删除', iconCls: 'icon-remove', handler: function () {
                deleteProject();
            }
            }, '-',
            {
                text: '查看', iconCls: 'icon-more', handler: function () {
                opendetailWin();
            }
            }, '-',
            {
                text: '刷新', iconCls: 'icon-reload', handler: function () {
                $('#dglist').datagrid('load', { total: 0});
                // $('#dglist').datagrid("load");
            }
            }, '-'
            ,
            {
                text: '导入生产订单', iconCls: 'icon-lock', handler: function () {
                openWin("dglist", "importWin", "导入生产订单", 400, 400, "importForm", "import");
            }
            },
            '-' ,
            {
                text: '搜 索', iconCls: 'icon-search', handler: function () {
                $('#findWorkOrderWin').show().window('open');
            }
            },
            '-'
        ],
    });
    $('#dglist').datagrid('getPager').pagination({//分页栏下方文字显示
        beforePageText: '第',
        afterPageText: '页，总共 {pages}页',
        displayMsg: '当前显示从第{from}条到{to}条 共{total}条记录',
    });
    $('#dglist').datagrid({
        rowStyler: function (index, row) {
            if (row.workOrderStatus == 'Ready') return 'background-color:#3EF907;';
        }
    });

});

//获取日期
function getDate(value){
    var unixTimestamp = new Date(value);
    return unixTimestamp.toLocaleString();
}

//查找工单
function findWorkOrder(){
    var findMaterialNumber=$("#findMaterialNumber").val();
    var findPartName=$("#findPartName").val();
    var findMaterial=$("#findMaterial").val();
    var findMaterialSpec=$("#findMaterialSpec").val();
    var findChartNumber=$("#findChartNumber").val();
    var findArrivalDate=$("#findArrivalDate").datebox('getValue');
    $('#dglist') .datagrid('load',{findMaterialNumber:findMaterialNumber, findPartName:findPartName, findMaterial:findMaterial, findMaterialSpec:findMaterialSpec, findChartNumber:findChartNumber, findArrivalDate:findArrivalDate});
}

//删除，可批量删除
function deleteUser() {
    var ids = $.getManyRecords("dglist")
    $.messager.confirm('确认', '您确认想要删除记录吗？', function (r) {
        if (r) {
            $.ajax({
                type: "POST",
                url: "delete",
                data: {ids: ids},
                timeout: 20000,
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (data.msg == "success") {
                        $.messager.alert("提示", "删除成功！", "info", function () {
                            window.location.reload();
                        })
                    } else {
                        $.messager.alert("提示", "删除失败！", "info", function () {
                            window.location.reload();
                        });
                    }

                },
                error: function () {
                    $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
                }
            })
        }
    });
}


//删除项目

function deleteProject() {
    var rows = $("#dglist").datagrid("getChecked");
    var ids = $.getManyRecords("dglist")
    var chartNumbers = "";
    for (var i = 0; i < rows.length; i++) {
        chartNumbers = chartNumbers + rows[i].chartNumber + ",";
    }

    $.messager.confirm('确认', '您确认想要删除记录吗？', function (r) {
        $.ajax({
            type: "POST",
            url: "deleteWorkOrder",
            data: {ids: ids, chartNumbers: chartNumbers},
            timeout: 20000,
            dataType: "json",
            cache: false,
            success: function (data) {
                if (data.msg == "success") {
                    $.messager.alert("提示", "删除成功！", "info", function () {
                        $("#dglist").datagrid('reload');
                    });
                } else {
                    $.messager.alert("提示", "删除失败！", "info", function () {
                        $("#dglist").datagrid('reload');
                    });
                }

            },
            error: function () {
                $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
            }
        })
    })
}

//打开修改工艺信息的窗口
function openEditTechnologyListWin() {
    if (!$.getSingleRecord("dglist")) {
        return;
    }
    var row = $.getSingleRecord("dglist");
    $("#showWorkOrderId").val(row.id);
    $("#showProjectId").combobox("select", row.productOrder.id);
    $("#showProjectId").combobox('disable');
    $("#showPartsName").textbox("setValue", row.partName);
    $('#showPartsName').textbox('textbox').attr('disabled', true);
    $("#showChartNumber").textbox("setValue", row.chartNumber);
    $('#showChartNumber').textbox('textbox').attr('disabled', true);
    $("#showOderNumber").textbox("setValue", row.oderNumber);
    $('#showOderNumber').textbox('textbox').attr('disabled', true);
    $('#technologydglist').datagrid({url: 'findProcessFlowByWorkOrderId'});
    $('#technologydglist').datagrid('load', {workOrderId: row.id});
    if ($("#updateTechnology").length <= 0) {
        $("#btnpanel").append("<a id='updateTechnology'  iconCls='icon-edit' onclick='openEditTechnologyWin()'  class='easyui-linkbutton'>修改</a>")
        $.parser.parse("#btnpanel");
    }

    $('#addTechnologyWin').show().window('open');


}

//确认修改工艺
function editTechnology() {
    $('#editTechnologyForm').form('submit', {
        onSubmit: function () {
            if (!$(this).form('enableValidation').form('validate')) {
                return $(this).form('enableValidation').form('validate');
            }
            $.ajax({
                type: "POST",
                url: "updateProcessFlow",
                data: $("#editTechnologyForm").serialize(),
                dataType: "json",
                success: function (data) {
                    if (data.msg == "success") {
                        $.messager.alert("提示", "修改成功！", "info", function () {
                            cancelWin('editTechnologyWin', 'editTechnologyForm');
                            $('#technologydglist').datagrid('load', {workOrderId: $.getSingleRecord("dglist").id});
                        })
                    } else {
                        $.messager.alert("提示", "修改失败,失败原因:"+data.result, "info", function () {
                            $('#technologydglist').datagrid('load', {workOrderId: $.getSingleRecord("dglist").id});
                        })
                    }
                },
                error: function () {
                    $.messager.alert("提示", "出现了不可预知的错误，请刷新重试！");
                }
            });
        }
    })
}

//打开修改工艺信息的窗口
function openEditTechnologyWin() {
    if (!$.getSingleRecord("technologydglist")) {
        return;
    }
    var id = $.getSingleRecord("technologydglist").id;
    $.ajax({
        type: "POST",
        url: "toUpdateProcessFlow",
        data: {id: id},
        timeout: 20000,
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.msg == "success") {
                // $("#tpId").val(data.tp.id);
                $("#tpId").textbox("setValue", data.processFlow.id);
                $("#workOrderId").textbox("setValue", $.getSingleRecord("dglist").id);

                $("#tpProductionProcesses").textbox("setValue", data.processFlow.productionProcesses);
                $("#tpSequenceNumber").textbox("setValue", data.processFlow.sequenceNumber);
                $("#tpProcessContent").textbox("setValue", data.processFlow.processContent);
                $("#tpProductionQuantity").textbox("setValue", data.processFlow.productionQuantity);
                $("#tpEstimateTime").textbox("setValue", data.processFlow.estimateTime);
                $("#tpOperator").textbox("setValue", data.processFlow.operator);
                $("#tpId").next().hide();
                $("#workOrderId").next().hide();
                $("#editTechnologyWin").show().window("open");

            } else {
                $.messager.alert("提示", "获取本条记录信息失败失败！", "info", function () {
                    window.location.reload();
                });
            }

        },
        error: function () {
            $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
        }
    })
}
function getDate(value){
    var unixTimestamp = new Date(value);
    return unixTimestamp.toLocaleString();
}

//修改项目信息
function editProject() {
    if (!$.getSingleRecord("dglist")) {
        return;
    }
    var id = $.getSingleRecord("dglist").id;
    $.ajax({
        type: "POST",
        url: "toUpdate",
        data: {id: id},
        timeout: 20000,
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.msg == "success") {
                // alert(data.project.id);
                $("#id").textbox("setValue", data.workOrder.id);
                $("#poId").textbox("setValue", data.workOrder.productOrder.id);
                $("#materialNumber").textbox("setValue", data.workOrder.materialNumber);
                $("#partName").textbox("setValue", data.workOrder.partName);
                $("#material").textbox("setValue", data.workOrder.material);
                $("#materialSpec").textbox("setValue", data.workOrder.materialSpec);
                $("#chartNumber").textbox("setValue", data.workOrder.chartNumber);
                $("#oderNumber").textbox("setValue", data.workOrder.oderNumber);
                $("#unit").textbox("setValue", data.workOrder.unit);
                $("#remarksFig").textbox("setValue", data.workOrder.remarksFig);
                console.info(getDate(data.workOrder.arrivalDate));
                $('#arrivalDate').datebox('setValue', getDate(data.workOrder.arrivalDate));
                openWin("dglist", "updateProjectWin", "修改项目基本信息", "450px", "470px", "updateProjectForm", "update");
                $("#id").next().hide();
                $("#poId").next().hide();
                $("#updateProjectWin").show().window("open");
            } else {
                $.messager.alert("提示", "获取本条记录信息失败失败！", "info", function () {
                    window.location.reload();
                });
            }

        },
        error: function () {
            $.messager.alert("提示", "出现了不可预知的错误，请重新操作！");
        }
    })
}

function opendetailWin() {
    $("#detailWin").show().window("open");
}

function opendetailWin() {
    // $("#editRoleForm").form("reset");
    if (!$.getSingleRecord("dglist")) {
        $('#detailWin').window('close');
        return;
    }
    $('#detailWin').window('open');
    var row = $.getSingleRecord("dglist");
    $('#detailList').datagrid({
        url: "findProcessFlowByWorkOrderId",
        method: "POST",
        striped: true,
        loadMsg: "努力加载中...",
        queryParams: {workOrderId: row.id},
        fitColumns: true,//是否自动填充适合屏幕
        autoRowHeight: false,
        columns: [[
            {field: 'sequenceNumber', title: '序号', sortable: true, align: "center"},
            {field: 'productionProcesses', title: '工序', sortable: true, align: "center"},
            {field: 'processContent', title: '工艺内容', sortable: true, align: "center"},
            {field: 'productionQuantity', title: '生产数量', sortable: true, align: "center"},
            {
                field: 'estimateTime', title: '预估工时', sortable: true, align: "center",
                formatter: function (value, row, index) {
                    return (row["estimateTime"]).toFixed(2);
                }
            },
            {field: 'operator', title: '操作员', sortable: true, width: 100, align: "center"},
            {field: 'receptionConfirmation', title: '下工段接收确认', sortable: true, width: 100, align: "center"},
            {field: 'remarks', title: '备注', sortable: true, width: 100, align: "center"}
        ]],
    });
}
